﻿using Newtonsoft.Json;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RabbitMQSenderDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectExchangeSendMsg();
        }

        /// <summary>
        /// 连接配置
        /// </summary>
        private static readonly ConnectionFactory factory = new ConnectionFactory()
        {
            HostName = "127.0.0.1",
            UserName = "whl",
            Password = "123456",
            Port = 5672,
            VirtualHost = "/"
            //HostName = "10.0.102.73",
            //UserName = "wxadmin",
            //Password = "wxadmin",
            //Port = 5672,
            //VirtualHost = "/"
        };
        /// <summary>
        /// 路由名称
        /// </summary>
        const string ExchangeName = "ClassTicket.Exchange";
        //队列名称
        const string QueueName = "ClassTicket.Queue";
        //路由规则
        const string RoutingKey = "#";
        public static void DirectExchangeSendMsg()
        {
            try
            {
                using (IConnection conn = factory.CreateConnection())
                {
                    using (IModel channel = conn.CreateModel())
                    {
                        //channel.ExchangeDeclare(ExchangeName, ExchangeType.Direct);
                        channel.ExchangeDeclare(ExchangeName, ExchangeType.Direct, true, false, null);
                        while (true)
                        {
                            string customStr = Console.ReadLine();
                            RequestMsg requestMsg = new RequestMsg();
                            //requestMsg.Name = string.Format("Name_{0}", customStr);
                            //requestMsg.Code = string.Format("Code_{0}", customStr);
                            string jsonStr = JsonConvert.SerializeObject(customStr);
                            byte[] bytes = Encoding.UTF8.GetBytes(jsonStr);

                            //设置消息持久化
                            IBasicProperties properties = channel.CreateBasicProperties();
                            properties.DeliveryMode = 2;
                            channel.BasicPublish(ExchangeName, RoutingKey, properties, bytes);
                            Console.WriteLine("消息已发送：" + requestMsg.ToString());
                        }
                    }
                }
            }
            catch (Exception e1)
            {
                Console.WriteLine(e1.ToString());
            }
            Console.ReadLine();
        }

    }
}
